
package cnki.kg.demo.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.RandomAccessFile;

public class FileHelper {

	private static final Logger logger = LoggerFactory.getLogger("fileHelper");
	/**
	 * 创建文件
	 * 
	 * @param fileName
	 * @return
	 */
	public static boolean createFile(String filePath) throws Exception {
		boolean flag = false;
		File fileName=new File(filePath);
		try {
			if (!fileName.exists()) {
				fileName.createNewFile();
				flag = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

	/**
	 * 读TXT文件内容
	 * 
	 * @param fileName
	 * @return
	 */
	public static String readTxtFile(String filePath) throws Exception {
		String result = null;
		FileReader fileReader = null;
		BufferedReader bufferedReader = null;
		try {
			File fileName=new File(filePath);
			fileReader = new FileReader(fileName);
			bufferedReader = new BufferedReader(fileReader);
			try {
				String read = null;
				while ((read = bufferedReader.readLine()) != null) {
					result = result + read + "\r\n";
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (bufferedReader != null) {
				bufferedReader.close();
			}
			if (fileReader != null) {
				fileReader.close();
			}
		}
		System.out.println("读取出来的文件内容是：" + "\r\n" + result);
		return result;
	}

	public static boolean writeTxtFile(String content, String filePath,boolean isUnicode) throws Exception {
		RandomAccessFile mm = null;
		boolean flag = false;
		FileOutputStream o = null;
		try {
			File fileName=new File(filePath);
			if(!fileName.exists())
			{
				fileName.createNewFile();
			}
			o = new FileOutputStream(fileName);
			if(isUnicode)
			{
				o.write(content.getBytes("GBK"));
			}else {
				o.write(content.getBytes("UTF-8"));
			}
			o.close();
			flag = true;
		} catch (Exception e) {
			logger.error(e.toString());
			e.printStackTrace();
		} finally {
			if (mm != null) {
				mm.close();
			}
		}
		return flag;
	}
	public static boolean deleteTxtFile(String filePath) throws Exception {
		File fileName=new File(filePath);
		try {
			if (!fileName.exists()) {
				return false;
			}
			fileName.delete();
			} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}
}
